﻿using QD.PushManager.DB;
using QD.PushManager.Domain;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace QD.PushManager.Manager
{
    /// <summary>
    /// 订阅宝公司操作
    /// </summary>
    public static class CompanyManager
    {
        static string TableName { get { return "sql_s003.dbo.vifo_union_website"; } }
        /// <summary>
        /// 获取推送的用户
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="page"></param>
        /// <returns></returns>
        public static Company GetPushCompany(int userId, int page)
        {
            var sb = new StringBuilder();
            sb.Append("select * from (");
            sb.Append("select top 5 UserID,GroupId,GroupID_WeApp,CellPhone,Plnum1,ShortName,Star1,ApiUrl,Tag_DYB as UserTag,PayMethod as ProductCount,ShippingMethod as ArticleCount,SiteEncoding as appid,Speciality as accesstoken,Tag as wx_name");
            sb.Append(",row_number() over(order by plnum1, userid desc) as row_num");
            sb.AppendFormat(" from {0} where", TableName);
            sb.Append(" Deleted = 0 and ShortName != ''");
            sb.Append(" and BusinessType = ''");                        //不能填微信账户
            sb.Append(" and SiteEncoding != '' and Speciality != ''");  //API认证号
            sb.Append(" and ApiTag = 0");
            sb.Append(" and plnum1 is not null and DATEDIFF(mi, CONVERT(varchar, getdate(), 23) + ' ' + plnum1, getdate()) > 0");
            sb.Append(" and(");
            sb.Append(" datediff(dd, SiteCreateTime, getdate()) < 1");      //微推广客户
            sb.Append(" or datediff(dd, LastSynTime, getdate()) < 1");      //微街宝客户
            sb.Append(" or datediff(dd, ExpiredTime_DYB, GETDATE()) < 1");  //订阅宝客户
            sb.Append(" or UserID in (select UserID from sql_s003.dbo.vifo_groups where GroupType = 20 and ExpireTime > GETDATE())");    //小程序方案客户
            sb.Append(")");
            if (userId > 0)
            {
                sb.AppendFormat(" and userid={0}", userId);
                page = 1;
            }
            sb.AppendFormat(" order by plnum1,UserID desc ) as t where row_num = {0}", page);

            using (var db = new ShtDatabase())
            {
                return db.SingleOrDefault<Company>(sb.ToString());
            }
        }

    }
}